import axios from 'axios'
import {ElMessage} from 'element-plus'
import {useUserStore} from '@/pinia/modules/user'
import {emitter} from '@/utils/bus'
import router from "@/router/router";
import { message } from '@/utils/message.js'

// 创建 axios 实例
const request = axios.create({
    baseURL: process.env.VUE_APP_BASE_API,
    timeout:60000 // 请求超时时间
})

let acitveAxios = 0
let timer

const showLoading = () => {
    acitveAxios++
    if (timer) {
        clearTimeout(timer)
    }

    timer = setTimeout(() => {
        if (acitveAxios > 0) {
            emitter.emit('showLoading')
        }
    }, 400)
}

const closeLoading = () => {
    acitveAxios--
    if (acitveAxios <= 0) {
        clearTimeout(timer)
        emitter.emit('closeLoading')
    }
}

// http request 拦截器
request.interceptors.request.use(
    config => {
        if (!config.donNotShowLoading) {
            showLoading()
        }
        const userStore = useUserStore()
        config.headers = {
            'Content-Type': 'application/json',
            'username': userStore.GetUserInfo(),
            'token': userStore.token,
            ...config.headers
        }
        return config
    },
    error => {
        closeLoading()
        ElMessage({
            showClose: true,
            message: error,
            type: 'error'
        })
        return error
    }
)

// http response 拦截器
request.interceptors.response.use(
    response => {
        const userStore = useUserStore()
        return response
    },
    error => {
        closeLoading()
        switch (error.response.status) {
            case 500:
                message.fail('服务器发生错误。')
                break
            case 401:
                if (error.response.data.code) {
                    if (error.response.data.code === 1005) {
                        ElMessage({
                            type: 'fail',
                            message: error.response.data.msg
                        })
                        router.push({"name":"Login"})
                        break
                    }
                }
                break
            case 400:
                ElMessage({
                    type: 'fail',
                    message: error
                })
                break


        }
        closeLoading()
        return error.response
    }
)

export default request
